# -*- coding: UTF-8 -*-

from .BaseService import BaseService

class WechatUserOnlineActionHandlerService(BaseService):

    def actionHandler(self, uin):
        userinfoDetailDO = self.core.loader.instance('do', 'UserinfoDetail').get(uin)
        if userinfoDetailDO is None:
            return self.core.lib.outputobj(False, '用户登录信息获取失败')

        retryNum = 0
        operateMsg = []
        wechatUserMsgInterpterService = self.core.loader.service('WechatUserMsgInterpterService')
        while True:
            statusCheckRes = self._onlineStatusCheck(userinfoDetailDO)
            if not statusCheckRes.success:
                return statusCheckRes

            syncActionRes = self._syncActionInfo(userinfoDetailDO)
            if not syncActionRes.success:
                continue
            if syncActionRes.data.has_key('AddMsgList'):
                wechatUserMsgInterpterService.msgHandler(uin, syncActionRes.data['AddMsgList'])

        return self.core.lib.outputobj(False, '异常退出')


    def _onlineStatusCheck(self, userinfoDetailDO):
        url = '%s/synccheck' % userinfoDetailDO.login_url
        params = {
            'r' : int(self.core.loader.module('time').time() * 1e3),
            'skey' : userinfoDetailDO.skey,
            'sid' : userinfoDetailDO.sid,
            'uin' : userinfoDetailDO.uin,
            'deviceid' : userinfoDetailDO.device_id,
            'synckey' : userinfoDetailDO.status_sync_key,
            '_' : userinfoDetailDO.login_time
        }
        userinfoDetailDO.login_time += 1
        request = self.core.loader.lib('request', transport_core = True)
        responseRes = request.sGet(mSession = userinfoDetailDO.session, url = url, params = params, headers = self.core.config.DEFAULT_HEADER, timeout = self.core.config.TIMEOUT)
        if not responseRes.success:
            return self.core.lib.outputobj(False, responseRes.message, -1)

        matches = self.core.loader.module('re').search(r'window.synccheck={retcode:"(\d+)",selector:"(\d+)"}', responseRes.data.text)
        if matches is None:
            return self.core.lib.outputobj(False, '未匹配到在线状态信息', None, -1)

        if matches.group(1) != '0':
            return self.core.lib.outputobj(False, '该用户已经不在线，状态码[%s]' % matches.group(1), None, int(matches.group(1)))

        return self.core.lib.outputobj(True, '在线状态同步成功', matches.group(2))


    '''
    ... 请求正常，返回参数content的值
    ... {
    ...     "Profile": {
    ...         "BitFlag": 0,
    ...         "UserName": {
    ...             "Buff": ""
    ...         },
    ...         "HeadImgUrl": "",
    ...         "BindMobile": {
    ...             "Buff": ""
    ...         },
    ...         "Status": 0,
    ...         "Alias": "",
    ...         "BindUin": 0,
    ...         "PersonalCard": 0,
    ...         "Signature": "",
    ...         "Sex": 0,
    ...         "NickName": {
    ...             "Buff": ""
    ...         },
    ...         "BindEmail": {
    ...             "Buff": ""
    ...         },
    ...         "HeadImgUpdateFlag": 0
    ...     },
    ...     "SyncKey": {
    ...         "Count": 7,
    ...         "List": [
    ...             {
    ...                 "Val": 685753629,
    ...                 "Key": 1
    ...             },
    ...             {
    ...                 "Val": 685754985,
    ...                 "Key": 2
    ...             },
    ...             {
    ...                 "Val": 685754971,
    ...                 "Key": 3
    ...             },
    ...             {
    ...                 "Val": 685754825,
    ...                 "Key": 11
    ...             },
    ...             {
    ...                 "Val": 1522326313,
    ...                 "Key": 201
    ...             },
    ...             {
    ...                 "Val": 1522312082,
    ...                 "Key": 1000
    ...             },
    ...             {
    ...                 "Val": 1522312154,
    ...                 "Key": 1001
    ...             }
    ...         ]
    ...     },
    ...     "ModContactCount": 0,
    ...     "SKey": "",
    ...     "ContinueFlag": 0,
    ...     "BaseResponse": {
    ...         "ErrMsg": "",
    ...         "Ret": 0
    ...     },
    ...     "AddMsgList": [
    ...         {
    ...             "ImgWidth": 0,
    ... "FromUserName": "@8c1e63436eabc8250d38712bc76351af90d3a74f618d96b003f6f08201707222", #如果是群消息，格式为"@@7a69eb63860e3362826c5c66b496285c61e8a5ddd93960752d463f0055b90871"
    ...             "PlayLength": 0,
    ...             "OriContent": "",
    ...             "RecommendInfo": {
    ...                 "UserName": "",
    ...                 "Province": "",
    ...                 "City": "",
    ...                 "Scene": 0,
    ...                 "QQNum": 0,
    ...                 "Content": "",
    ...                 "Alias": "",
    ...                 "OpCode": 0,
    ...                 "Signature": "",
    ...                 "Ticket": "",
    ...                 "Sex": 0,
    ...                 "NickName": "",
    ...                 "AttrStatus": 0,
    ...                 "VerifyFlag": 0
    ...             },
    ...             "Content": "ceshi",
    ...             "StatusNotifyUserName": "",
    ...             "StatusNotifyCode": 0,
    ...             "NewMsgId": 7633774691804190000,
    ...             "Status": 3,
    ...             "VoiceLength": 0,
    ...             "ToUserName": "filehelper", #如果是群消息，格式为"@@7a69eb63860e3362826c5c66b496285c61e8a5ddd93960752d463f0055b90871"
    ...             "ForwardFlag": 0,
    ...             "AppMsgType": 0,
    ...             "Ticket": "",
    ...             "EncryFileName": "",
    ...             "AppInfo": {
    ...                 "Type": 0,
    ...                 "AppID": ""
    ...             },
    ...             "Url": "",
    ...             "ImgStatus": 1,
    ...             "MsgType": 1,
    ...             "ImgHeight": 0,
    ...             "MediaId": "",
    ...             "MsgId": "7633774691804189824",
    ...             "FileName": "",
    ...             "HasProductId": 0,
    ...             "FileSize": "",
    ...             "CreateTime": 1522326313,
    ...             "SubMsgType": 0
    ...         }
    ...     ],
    ...     "SyncCheckKey": {
    ...         "Count": 7,
    ...         "List": [
    ...             {
    ...                 "Val": 685753629,
    ...                 "Key": 1
    ...             },
    ...             {
    ...                 "Val": 685754985,
    ...                 "Key": 2
    ...             },
    ...             {
    ...                 "Val": 685754971,
    ...                 "Key": 3
    ...             },
    ...             {
    ...                 "Val": 685754825,
    ...                 "Key": 11
    ...             },
    ...             {
    ...                 "Val": 1522326313,
    ...                 "Key": 201
    ...             },
    ...             {
    ...                 "Val": 1522312082,
    ...                 "Key": 1000
    ...             },
    ...             {
    ...                 "Val": 1522312154,
    ...                 "Key": 1001
    ...             }
    ...         ]
    ...     },
    ...     "AddMsgCount": 1,
    ...     "ModChatRoomMemberCount": 0,
    ...     "ModContactList": [],
    ...     "DelContactList": [],
    ...     "ModChatRoomMemberList": [],
    ...     "DelContactCount": 0
    ... }
    '''
    def _syncActionInfo(self, userinfoDetailDO):
        url = '%s/webwxsync' % userinfoDetailDO.login_url
        params = {
            'sid' : userinfoDetailDO.sid,
            'skey' : userinfoDetailDO.skey,
            'pass_ticket' : userinfoDetailDO.pass_ticket
        }
        postData = {
            'BaseRequest' : userinfoDetailDO.base_request_params,
            'SyncKey' : userinfoDetailDO.action_sync_key,
            'rr' : ~int(self.core.loader.module('time').time())
        }

        request = self.core.loader.lib('request', transport_core = True)
        responseRes = request.sPost(mSession = userinfoDetailDO.session, url = url, params = params, data = postData, headers = self.core.config.JSON_UTF8_HEADER, timeout = self.core.config.TIMEOUT)
        if not responseRes.success:
            return self.core.lib.outputobj(False, responseRes.message)
        
        decodeContentRes = request.decodeJsonContent(responseRes.data, errors = 'replace')
        if not decodeContentRes.success or not isinstance(decodeContentRes.data, dict):
            return self.core.lib.outputobj(False, '解析活动信息失败，失败原因：%s' % decodeContentRes.message)

        content = decodeContentRes.data
        errcode = int(content.get('BaseResponse', {}).get('Ret', -1))
        if errcode != 0:
            return self.core.lib.outputobj(False, '信息获取失败，错误码[%d]' % errcode)

        userinfoDetailDO.action_sync_key = content['SyncKey']
        userinfoDetailDO.status_sync_key = '|'.join(['%s_%s' % (i['Key'], i['Val']) for i in content['SyncCheckKey']['List']])
        return self.core.lib.outputobj(True, '成功获取用户活动信息', content)    
